const app = getApp();
Component({
    properties: {
        max: {
            type: Number,
            value: 3
        },
        gridConfig: {
            column: 4,
            width: 160,
            height: 160,
        },
        value: {
            type: String,
            value: ``,
            observer(value) {
                this.initFileList(value);
            }
        },
    },
    data: {
        originFiles: [],
    },
    methods: {
        initFileList(value) {
            if (value && value.length > 0 && value.startsWith('/')) {
                const images = value.split(',').map((img) => ({
                    url: app.getImageUrl(img),
                    name: img.substr(img.lastIndexOf('/')),
                    data: img
                }));
                
                this.setData({
                    originFiles: images
                });
            }
        },
        /**
         * 上传成功
         * @param {*} e 
         */
        handleSuccess(e) {
            const files = e.detail.files;
            let file = files[files.length - 1];
            let fileList = this.data.originFiles;
            app.httpUpload(file.url).then((res) => {
                fileList.push({
                    url: app.getImageUrl(res.data),
                    name: file.name,
                    type: file.type,
                    data: res.data
                });
                this.setData({
                    originFiles: fileList,
                });
                const data = fileList.map((i) => (i.data)).join(',');
                this.triggerEvent('event', data);
            });
        },

        /**
         * 删除文件
         * @param {*} e 
         */
        handleRemove(e) {
            const index = e.detail.index;
            const originFiles = this.data.originFiles;
            originFiles.splice(index, 1);
            this.setData({
                originFiles,
            });
            const data = originFiles.map((i) => (i.data)).join(',');
            this.triggerEvent('event', data);
        }
    }
});